<?php

namespace Destroyer\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Route;
use Symfony\Component\HttpFoundation\Response;
use App\Admin\Admin;

use Destroyer\Models\User;
use Destroyer\Models\Role;
use Destroyer\Models\Menu;
use Destroyer\Models\RoleMenu;

class RBAC
{
    // 白名单路由
    private static array $whiteRouteName = [
        'system.nav.__invoke',
        'system.profile.show',
    ];

    public function handle(Request $request, Closure $next): Response
    {
        $routeName = getRouteNameFromRouteObject(Route::current());

        /**
         * RBAC白名单路由
         * 所有用户都有的基础权限，比如个人资料，个人菜单
         */
        if( in_array($routeName, static::$whiteRouteName) ){
            return $next($request);
        }

        // 
        $permission = Menu::where('code', $routeName)->select(['id', 'type', 'title', 'code'])->first();
        if( !$permission ){
            return response()->json(['code' => 500, 'message' => '该功能未加入菜单']);
        }

        // 用户所有的角色
        $user = Auth::guard('admin')->user();


        // 判断用户持有的角色中 是否有含有当前路由(菜单)权限的
        if( count($user->role_ids) > 0 ){
            $permissionExists = RoleMenu::where('menu_id', $permission->id)->whereIn('role_id', $user->role_ids)->exists();
            if( $permissionExists ){
                return $next($request);
            }
        }

        return response()->json([
            'code' => 403,
            'message' => "当前用户没有该功能 `{$permission->title}` 操作权限"
        ]);
    }
}
